package com.hhit.collaborative_learning.communication;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.hhit.collaborative_learning.dao.CoopTalkDao;
import com.hhit.collaborative_learning.dao.CoopTaskDao;
import com.hhit.collaborative_learning.dao.impl.CoopTalkDaoImpl;
import com.hhit.collaborative_learning.dao.impl.CoopTaskDaoImpl;
import com.hhit.collaborative_learning.utils.DBAccess;
import com.hhit.collaborative_learning.utils.JsonUtil;
import com.hhit.collaborative_learning.utils.ResponseUtil;
import com.mysql.jdbc.StringUtils;

/**
 * Servlet implementation class GetCoopTaskServlet
 */
@WebServlet("/communication/GetCoopTaskServlet")
public class GetCoopTaskServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetCoopTaskServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String find="";
		String task_id=request.getParameter("task_id");
		String projID=request.getParameter("projID");
		String tyle=request.getParameter("tyle");
		if(!StringUtils.isNullOrEmpty(task_id)){
			find=" ID="+task_id;
		}else{
			if(!StringUtils.isNullOrEmpty(projID)){
				find=" pid="+projID;
				if(!StringUtils.isNullOrEmpty(tyle)){
					find+=" and State like '"+tyle+"'";
				}
			}
		}
		
		JSONObject jobj = new JSONObject();
		Connection con = DBAccess.getInstance().getConn();
		CoopTaskDao td=new CoopTaskDaoImpl();
		ResultSet re=td.query(con, 0, 0, find, "desc", " CreatedOn ");
		try {
			JSONArray tArray=JsonUtil.formatRsToJsonArray(re);
			jobj.put("taskArray", tArray.toString());
			ResponseUtil.write(response, jobj.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBAccess.getInstance().close(con, null, re);
			System.out.println("coopTalk json "+jobj.toString());
		}
	}

}
